package com.nantai.jiafang.nantaijiafang.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.MyApplication;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.bean.FabricBatchInfo;
import com.nantai.jiafang.nantaijiafang.bean.ProductionOrderInfo;
import com.nantai.jiafang.nantaijiafang.bean.VersionInfo;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.User;
import com.nantai.jiafang.nantaijiafang.deviceManager.constant.Constans;
import com.nantai.jiafang.nantaijiafang.deviceManager.devicemanager.OperateActivity;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.Error;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.HttpClient;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.preference.PreferencesUtil;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.MessagePop;
import com.nantai.jiafang.nantaijiafang.dialog.CustomAlertDialog;
import com.nantai.jiafang.nantaijiafang.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//deviceManager
import info.hoang8f.android.segmented.SegmentedGroup;
import retrofit2.Call;


public class LoginActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    private EditText et_username, et_pwd;
    private Spinner company;
    private Button btn_login;
    private ProgressDialog progressDialog;
    private Context mcontext;
    private CheckBox cb_remember_pwd;
    private DbManager db;
    public static String userId = "";
    private SegmentedGroup loginType;
    private int login_type = 1;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private int company1;

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mcontext = LoginActivity.this;
        db = x.getDb(MyApplication.daoConfig);
        initViews();
        verifyStoragePermissions(this);
        checkUpdate();
    }

    private void checkUpdate(){

        RequestParams params = new RequestParams("http://5/AppHandler.ashx?opType=Version");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
//                Tools.showToast(mcontext, "数据同步成功");
//                anaylysisData(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String versionNo = jsonObject.getString("VersionNo");
                    String updateLog = jsonObject.getString("UpdateLog");
//                    String updateLog = "XXXX\nXXXX\nXXXX\nXXXX\n";
//                    String filePath = "http://115.29.224.146/SewageService/upload/apk/test.apk";
                    String filePath = jsonObject.getString("FilePath");
//                    updateLog = "2#3";
                    if(versionNo!=null&&!"".equals(versionNo)&&!versionNo.equals(getVersion(LoginActivity.this))){
                        VersionInfo info=new VersionInfo();
                        info.setVersion_path(filePath);
                        info.setVersion_log(updateLog);
                        info.setVersion_no(versionNo);
                        versionDialog(LoginActivity.this,info);
                    }
                }catch (Exception e){

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                onFailure();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

//        versionDialog(LoginActivity.this,new VersionInfo());
    }

    private void versionDialog(final Activity activity,
                               final VersionInfo info) {
        CustomAlertDialog.Builder builder = new CustomAlertDialog.Builder(
                activity);
        builder.setMessage(info.getVersion_log());


        builder.setbtn_left("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if(null == info.getVersion_path() || "".equals(info.getVersion_path())){
                    Toast.makeText(LoginActivity.this, "无效的下载路径，版本更新失败",
                            Toast.LENGTH_SHORT).show();
//                    startActivity(new Intent(LoginActivity.this,
//                            CustomerInfoActivity.class));
                } else {
                    Intent intent = new Intent(activity,
                            DownLoadActivity.class);
                    intent.putExtra("apkPath", "");
                    intent.putExtra("downLoadPath", info.getVersion_path());
                    activity.startActivity(intent);
                }
            }
        });

        builder.create().show();
    }

    public static String getVersion(Context mContext){
        PackageManager packageManager = mContext.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(mContext.getPackageName(),
                    0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        if(version!=null&&!"".equals(version))
            return version ;
        else
            return "1.0";
    }

    private void initViews() {
        cb_remember_pwd = (CheckBox) findViewById(R.id.cb_remember_pwd);
        et_username = (EditText) findViewById(R.id.et_username);
        company=(Spinner)findViewById(R.id.company);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        btn_login = (Button) findViewById(R.id.btn_login);
        TextView mTvVersion = (TextView)findViewById(R.id.tv_version);
        mTvVersion.setText("版本号:"+getVersion(this));

        progressDialog = new ProgressDialog(mcontext);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在登陆，请稍候");
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.show();
                if (et_username.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入用户名");
                } else if (et_pwd.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入密码");
                } else {
                    //TODO 登录方法
                    if (Tools.isNetAvailuable(mcontext)) {
                        login();
                    } else {
                        Tools.showToast(mcontext, "当前网络不可用，请检查网络");
                    }

                }
            }

        });
        getSaveLoginInfo();

        loginType = (SegmentedGroup)findViewById(R.id.segmented2);
       //loginType.check(R.id.ml_btn);
        loginType.check(R.id.device_btn);
        loginType.setTintColor(0xFF1b7ce8);
        loginType.setOnCheckedChangeListener(this);
    }

    //登录入口选择
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        et_username.setText("");
        et_pwd.setText("");

        switch (checkedId) {
            case R.id.ml_btn: {
                login_type=0;
            }
            break;
            case R.id.device_btn: {
                login_type=1;//选择设备
            }
            break;
            default:
                // Nothing to do
        }
        getSaveLoginInfo();
    }

    //获取是否有保存登录信息
    private void getSaveLoginInfo() {
        boolean is_save =PreferencesUtil.getIsSave(LoginActivity.this);
        if(is_save)
        {
            cb_remember_pwd.setChecked(true);
            User user =PreferencesUtil.getUser(LoginActivity.this);
            if(user!=null)
            {
                String userName=user.getUserName();
                String passWord=user.getPassWord();
                String sCompany=user.getCompany();
                et_username.setText(userName==null?"":userName);
                et_pwd.setText(passWord==null?"":passWord);

                String[] items=this.getResources().getStringArray(R.array.company);
                for (int i=0;i<items.length;i++)
                {
                    if(items[i].equals(sCompany==null?"":sCompany))
                    {
                        company.setSelection(i,false);
                    }
                }
            }
        }
    }

    private void login() {
        Log.e("xuxin","login_type = "+login_type);
        Log.e("xuxin","company = "+company.getSelectedItem());
        if(company.getSelectedItem().equals("瀚隆"))
        {
           // Constans.BASE_URL="http://222.188.95.94:8069/hlService/index.php/UserApi/";
            Constans.BASE_URL="http://58.215.221.42:5050/ntService/index.php/UserApi/";
        }
        else
        {
            //Constans.BASE_URL="http://58.214.250.250:8010/ntService/index.php/UserApi/";

            Constans.BASE_URL="http://58.215.221.42:5050/ntService/index.php/UserApi/";
        }
        if(login_type==0)
        {
            //面料管理登录
            RequestParams params = new RequestParams(IConstant.URL_LOGIN + "login");
            //params.setSslSocketFactory(...); // 设置ssl
            params.addBodyParameter("loginName", et_username.getText().toString());
            params.addBodyParameter("password", et_pwd.getText().toString());

            System.out.println("请求的URL：" + params.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("返回结果：" + result);
                    String results[] = result.split(":");
                    if (results[0].equals("1")) {
                        Tools.showToast(mcontext, "登录成功");
                        SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(IConstant.SP_USERNAME, results[1]);
                        editor.commit();
                        User user = new  User();
                        PreferencesUtil.setIsSave(LoginActivity.this, cb_remember_pwd.isChecked());
                        user.setUserName(et_username.getText().toString());
                        user.setPassWord(et_pwd.getText().toString());
                        user.setCompany(company.getSelectedItem().toString());
                        PreferencesUtil.saveUser(LoginActivity.this, user);

                        userId = et_username.getText().toString();
                        progressDialog.setMessage("正在更新数据");
                        progressDialog.show();
                        updateDataFromNet();
                        startActivity(new Intent(mcontext, MainActivity.class));

                    } else {
                        progressDialog.dismiss();
                        Tools.showToast(mcontext, results[1]);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    progressDialog.dismiss();
                    Tools.showToast(mcontext, "请求出错，请重试");
                    //System.out.println("出错：" + ex.getCause().toString());

                }

                @Override
                public void onCancelled(CancelledException cex) {
                    progressDialog.dismiss();
                    Toast.makeText(mcontext, "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {
                    progressDialog.dismiss();
                }
            });
        }else
        {
            Map<String, String> params = new HashMap<>();
            String inputpassword = et_pwd.getText().toString();
            params.put("user_name", et_username.getText().toString());
            params.put("password", inputpassword);
            HttpClient client = new HttpClient(LoginActivity.this);
            Call call = client.service().login(params);

           client.request(call, new ResponseHandler<User>() {
               @Override
               public void onSuccess(User user) {
                   //登陆成功，保存用户信息
                   PreferencesUtil.setIsSave(LoginActivity.this, cb_remember_pwd.isChecked());
                   user.setUserName(et_username.getText().toString());
                   user.setPassWord(et_pwd.getText().toString());
                   user.setCompany(company.getSelectedItem().toString());
                   PreferencesUtil.saveUser(LoginActivity.this, user);
                   //设备管理登录
                   startActivity(new Intent(LoginActivity.this, OperateActivity.class));
                   progressDialog.dismiss();
               }

               @Override
               public void onFailure(int code, Error e) {
                   if(e.getCode().equals("CODE_USER_ERROR"))
                   {
                       progressDialog.dismiss();
                       MessagePop.ToastMessage(LoginActivity.this,e.getMessage());
                   }else
                   {
                       progressDialog.dismiss();
                       MessagePop.ToastMessage(LoginActivity.this, "网络异常");
                   }

               }
           });


        }
    }

    //同步数据
    private void updateDataFromNet() {

        RequestParams params = new RequestParams("http://222.188.95.94:7065/PushHandler.ashx");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                Tools.showToast(mcontext, "数据同步成功");
                anaylysisData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                onFailure();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //解析获取到的数据
    private void anaylysisData(String result) {
        Gson gson = new Gson();
        try {
            List<String> list_keys = new ArrayList<>();
            JSONObject jo = new JSONObject(result);
            Iterator it_color = jo.keys();
            while (it_color.hasNext()) {
                String key = it_color.next().toString();
                list_keys.add(key);
            }
            System.out.println("key:"+list_keys.size());
            for (int i = 0; i < list_keys.size(); i++) {
                if (list_keys.get(i).contains("ML")) {
                    List<FabricBatchInfo> list_fabric = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<FabricBatchInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_fabric.size(); j++) {
                        list_fabric.get(j).setIsRead("0");
                        list_fabric.get(j).setUserId(userId);
                    }
                    System.out.println("list1:"+list_fabric.size());
                    insertIntoFabricDB(list_fabric);
                }else if(list_keys.get(i).contains("SCDD")){
                    List<ProductionOrderInfo> list_production = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<ProductionOrderInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_production.size(); j++) {
                        list_production.get(j).setIsRead("0");
                        list_production.get(j).setUserId(userId);
                    }
                    System.out.println("list2:"+list_production.size());
                    insertIntoProductionDB(list_production);
                }
            }
            progressDialog.dismiss();
            startActivity(new Intent(mcontext, MainActivity.class));
            finish();
        } catch (JSONException e) {
            System.out.println("GSON出错");
            startActivity(new Intent(mcontext, MainActivity.class));
            finish();
        }
    }

    private void onFailure() {
        progressDialog.dismiss();
        //Tools.showToast(mcontext, "获取更新数据失败");
//        startActivity(new Intent(mcontext, MainActivity.class));
//        finish();
    }

    private void insertIntoFabricDB(List<FabricBatchInfo> list) {
        try {
            FabricBatchInfo info = list.get(0);
            List<FabricBatchInfo> list_db;
            list_db = db.selector(FabricBatchInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=",userId).findAll();
            if (list_db==null||list_db.size()==0){
                System.out.println("插入数量1："+list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错1");
        }
    }

    private void insertIntoProductionDB(List<ProductionOrderInfo> list) {
        try {
            ProductionOrderInfo info = list.get(0);
            List<ProductionOrderInfo> list_db;
            list_db = db.selector(ProductionOrderInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=",userId).findAll();
            if (list_db==null||list_db.size()==0){
                System.out.println("插入数量2："+list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错2");
        }
    }
}
